package com.jymj.common.config;

import com.alibaba.fastjson.JSON;
import com.jymj.dao.EnviorFileDao;
import com.jymj.dao.RenovatedDao;
import com.jymj.entity.Analysis.HjzzLogEntity;
import com.jymj.entity.Analysis.OnAccountEntity;
import com.jymj.entity.Analysis.RjhjzgtjEntity;
import com.jymj.entity.Analysis.TownProblemCountEntity;
import com.jymj.entity.CjEntity;
import com.jymj.entity.RenovatedFile;
import com.jymj.entity.dto.ReportDto;
import com.jymj.entity.dto.ScorebarDto;
import com.jymj.entity.landmanage.*;
import com.jymj.entity.vo.ComplaintsVo;
import com.jymj.entity.vo.ScoreVo;
import com.jymj.service.AnalysisService;
import com.jymj.service.EnviorFileService;
import com.jymj.service.EnviorSupvsService;
import com.jymj.service.ScoreService;
import com.jymj.utils.MonthUtils;
import com.jymj.utils.SmsUtils;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/*
 *  定时任务
 */
@Component
@Transactional(rollbackFor = RuntimeException.class)
public class TimingConfig {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private SmsConfig smsConfig;
    @Autowired
    private ScoreService scoreService;
    @Autowired
    private EnviorSupvsService enviorSupvsService;
    @Autowired
    private AnalysisService analysisService;
    @Autowired
    private EnviorFileService enviorFileService;
    @Autowired
    private EnviorFileDao enviorFileDao;
    @Autowired
    private RenovatedDao renovatedDao;

    /**
     * 计算扣分
     */
    //@Scheduled(cron = "0 30 23 * * ?")
    public void po() {
        logger.info("开始定时器时间:{}", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        //删除数据
        if (MonthUtils.isLastDayOfMonth(new Date())) {
            scoreService.deleteScorebar();
        }
        List<CjEntity> cjEntityList = scoreService.selectBycjCode();
        for (CjEntity cj : cjEntityList) {
            ScorebarEntity scorebarEntity = scoreService.scorebarByCode(cj, 1);
            ScorebarEntity scorebarEntity1 = scoreService.scorebarByCode(cj, 2);

            scoreService.saveCjScorebar(scorebarEntity);
            scoreService.saveCjScorebar(scorebarEntity1);

        }
        logger.info("结束定时器时间:{}", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    }

    /**
     * 扣分明细表
     */
    //@Scheduled(cron = "0 0 14 * * ?")
    @Scheduled(cron = "0 30 23 * * ?")
    public void  getScore(){
        logger.info("开始定时器时间:{}", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        List<CjEntity> cjEntityList = scoreService.selectBycjCode();
        for (CjEntity cj : cjEntityList) {
            ScoreEntity scoreEntity = scoreService.scoreByCode(cj, 1);
            ScoreEntity scoreEntity1 = scoreService.scoreByCode(cj, 2);

            scoreService.save(scoreEntity);
            scoreService.save(scoreEntity1);

        }
        logger.info("结束定时器时间:{}", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    }

    /**
     * 公厕扣分详情
     */
    //@Scheduled(cron = "0 22 11 * * ?")
    @Scheduled(cron = "0 40 23 * * ?")
    public void getGcScore(){
        logger.info("开始定时器时间:{}", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        List<ToiletRecordEntity> toiletRecordEntities = scoreService.queryRecord(new ScorebarDto());
        scoreService.saveToiletRecord(toiletRecordEntities);
        logger.info("结束定时器时间:{}", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    }

    /**
     * 每日查询当前整改情况表
     */
    //@Scheduled(cron = "0 14 10 * * ?")
    @Scheduled(cron = "0 51 22 * * ?")
    public void getZgqk(){
        List<ComplaintsVo> complaintsVos = enviorSupvsService.getZgqk();
        OnAccountEntity onAccountEntity = new OnAccountEntity();
        onAccountEntity.setJsontext(JSON.toJSONString(complaintsVos));
        onAccountEntity.setType(4);
        analysisService.saveGzwt(onAccountEntity);
    }

    /**
     * 综合扣分情况表
     */
    //@Scheduled(cron = "0 08 11 * * ?")
    @Scheduled(cron = "0 50 23 * * ?")
    public void getScoreTotal(){
        List<ScoreVo> scoreVos = scoreService.getZhscore(new ScorebarDto());
        scoreService.saveScoreTotal(scoreVos);
    }

    /**
     * 每月一号添加挂账数
     */
    //@Scheduled(cron = "0 0 1 1 * ?")
    //@Scheduled(cron = "0 57 14 * * ?")
    public void saveGzwt() {
        List<TownProblemCountEntity> countEntities = analysisService.queryWzg(new ReportDto());
        OnAccountEntity onAccountEntity = new OnAccountEntity();
        onAccountEntity.setJsontext(JSON.toJSONString(countEntities));
        onAccountEntity.setType(1);
        analysisService.saveGzwt(onAccountEntity);
    }

    /**
     * 定时每日 晚上8点 添加人居环境日志
     */
    @Scheduled(cron = "0 0 20 * * ? ")
    public void queryJournal() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        List<HjzzLogEntity> hjzzLogEntities = analysisService.queryLogByCun(df.format(new Date()), 1);
        List<HjzzLogEntity> hjzzLogEntities1 = analysisService.queryLogByCun(df.format(new Date()), 2);
        if (hjzzLogEntities == null || hjzzLogEntities.size() == 0) {
            return;
        } else {
            //添加到日志表
            PjEnviorSupvsLog pjEnviorSupvsLog = new PjEnviorSupvsLog();
            pjEnviorSupvsLog.setUptime(new Date());
            pjEnviorSupvsLog.setJsontext(JSON.toJSONString(hjzzLogEntities));
            pjEnviorSupvsLog.setType(1);
            enviorSupvsService.saveLog(pjEnviorSupvsLog);

            PjEnviorSupvsLog pjEnviorSupvsLog1 = new PjEnviorSupvsLog();
            pjEnviorSupvsLog1.setUptime(new Date());
            pjEnviorSupvsLog.setType(2);
            pjEnviorSupvsLog1.setJsontext(JSON.toJSONString(hjzzLogEntities1));
            enviorSupvsService.saveLog(pjEnviorSupvsLog1);
        }
    }


    /**
     * 定时发送下发短信
     */
    @Scheduled(cron = "0 0 21 * * ?")
    //@Scheduled(cron = "0 51 11 * * ?")
    public void querySms() {
        smsConfig.init(4);
        List<EnviorSmsEntity> list = enviorSupvsService.querySms();
        for (EnviorSmsEntity enviorSmsEntity : list) {
            if (enviorSmsEntity.getPhones().length == 0) {
                continue;
            }
            String[] strings = {enviorSmsEntity.getXzqmc(),
                    enviorSmsEntity.getCounts().toString(),
                    enviorSmsEntity.getCountsNew().toString(),
                    enviorSmsEntity.getCountsYq().toString()};
            SmsUtils.sendSmsInfo(enviorSmsEntity.getPhones(), strings);
        }
    }

    @Scheduled(cron = "0 30 8 ? * 1")
    public void querySmsZhen() {
        smsConfig.init(4);
        List<EnviorSmsEntity> list = enviorSupvsService.querySmsByZhen();
        for (EnviorSmsEntity enviorSmsEntity : list) {
            if (enviorSmsEntity.getPhones().length == 0) {
                continue;
            }
            Calendar   cal   =   Calendar.getInstance();
            cal.add(Calendar.DATE,   -1);
            String month = new SimpleDateFormat( "MM ").format(cal.getTime());
            String day = new SimpleDateFormat( "dd ").format(cal.getTime());
            String[] strings = {enviorSmsEntity.getXzqmc(),
                    month,day,
                    enviorSmsEntity.getCountsNew().toString(),
                    enviorSmsEntity.getCountsYq().toString()};
            SmsUtils.sendSmsInfo(enviorSmsEntity.getPhones(), strings);
        }
    }



    // 2、scorebar/queryRanking人居环境检查情况统计表 3、 analysis/queryRjhjzgtj 366个村人居环境整改情况统计表
    @Scheduled(cron = "0 10 2 * * ?")
    public void initJson() {
        List<ScoreZhenEntity> scoreZhenEntities = scoreService.queryRanking(null);
        List<RjhjzgtjEntity> rjhjzgtjEntities = analysisService.selectRjhjzgtj(null);
        OnAccountEntity onAccountEntity1 = new OnAccountEntity();
        OnAccountEntity onAccountEntity2 = new OnAccountEntity();
        onAccountEntity1.setJsontext(JSON.toJSONString(scoreZhenEntities)).setType(2);
        onAccountEntity2.setJsontext(JSON.toJSONString(rjhjzgtjEntities)).setType(3);
        analysisService.saveGzwt(onAccountEntity1);
        analysisService.saveGzwt(onAccountEntity2);

    }


    //删压缩包
    @Scheduled(cron = "0 0 0 * * ?")
    public void taskDelete() throws IOException {
        File path = new File(ResourceUtils.getURL("jar:").getPath());
        File monthZipFile = new File(path.getAbsolutePath().replace("jar:", "fileupload") + File.separator + "monthZipFile");
        logger.info(monthZipFile.getPath());
        FileUtils.deleteDirectory(monthZipFile);
        if (!monthZipFile.exists()) {
            monthZipFile.mkdir();
        }

    }

    //清除未绑定问题图片
    @Scheduled(cron = "0 50 2 1 * ?")
    @Transactional(rollbackFor = RuntimeException.class)
    public void fileDelete() throws FileNotFoundException {
        File genPath = new File(ResourceUtils.getURL("classpath:").getPath());
        if (!genPath.exists()) {
            genPath = new File("");
        }
        File savePath = new File(genPath.getAbsolutePath(), "fileupload" + File.separator + "enviorFile");
        List<PjEnviorFileEntity> pjEnviorFileEntities = enviorFileService.queryObjectBymsId(-1);
        if (pjEnviorFileEntities.size() > 0) {
            for (PjEnviorFileEntity pjEnviorFileEntity : pjEnviorFileEntities) {
                File file = new File(savePath + pjEnviorFileEntity.getPath());
                if (file.exists()) {
                    file.delete();
                }
                enviorFileService.delete(pjEnviorFileEntity.getId());
            }
        }
        List<RenovatedFile> files = enviorFileDao.getFiles(null, -1L);
        if (files.size() > 0) {
            files.forEach(file -> new File(file.getPath()).delete());
            enviorFileDao.deletefileById((Long[]) files
                    .stream().map(RenovatedFile::getId)
                    .collect(Collectors.toList()).toArray());
        }
        List<RenovatedFile> filesYl = renovatedDao.getFiles(null, -1L);
        if (filesYl.size() > 0) {
            filesYl.forEach(file -> new File(file.getPath()).delete());
            renovatedDao.deletefileById((Long[]) filesYl
                    .stream().map(RenovatedFile::getId)
                    .collect(Collectors.toList()).toArray());
        }
    }

    //清除问题qutype 4 -> 2 次数
    //@Scheduled(cron = "0 31 10 * * ?")
    @Scheduled(cron = "0 30 2 1 * ?")
    public void eliminate() {
        enviorSupvsService.updateCount3();
    }

}